package ArrayDeduplication.javaCode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ArrayDeduplication {

    /**
     * 常规想法---> set去重
     * @param nums
     * @return
     */
    public static int removeDuplicates(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int length = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!set.contains(nums[i])) {
                set.add(nums[i]);
                nums[length] = nums[i];
                length++;
            }
        }
        return length;
    }

    /**
     * 双指针 -> 通过判断相邻两个元素是否相同，来更新原数组
     * @param nums
     * @return
     */
    public static int removeDuplicates2(int[] nums) {
        int length = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i==0) {
                length++;
                continue;
            }
            if (nums[i-1] != nums[i]) {
                nums[length] = nums[i];
                length++;
            }
        }
        return length;
    }

    public static int removeDuplicates3(int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return 0;
        }
        int fast = 1, slow = 1;
        while (fast < n) {
            if (nums[fast] != nums[fast - 1]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }

    public static void main(String[] args) {
        int[] nums = {1,1,2};
        int length = removeDuplicates2(nums);
        System.out.println(length);
        System.out.println(Arrays.toString(nums));
    }
}
